/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.icanci.logparser.mq;

import cn.icanci.logparser.config.LogMqConfig;

import javax.annotation.Resource;

import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @author icanci
 * @date Created in 2021/04/18 23:53
 * @version 1.0
 */
@Component
public class LogProducer {
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送普通消息的示例
     * @param msg message
     */
    public void sendMessage(String msg) {
        this.rocketMQTemplate.convertAndSend(LogMqConfig.LOG_TOPIC, msg);
    }

    /**
     * 发送普通消息的示例
     * @param topic topic
     * @param msg message
     */
    public void sendMessage(String topic, String msg) {
        this.rocketMQTemplate.convertAndSend(topic, msg);
    }

    /**
     *  TODO 配置bean没有写 发送事务消息的示例，功能不需要
     *   配置见此处：https://blog.csdn.net/zxl646801924/article/details/105659481
     * @param topic topic
     * @param msg message
     * @throws InterruptedException
     */
    public void sendMessageInTransaction(String topic, String msg) throws InterruptedException {
        String[] tags = new String[] { "TagA", "TagB", "TagC", "TagD", "TagE" };
        for (int i = 0; i < 10; i++) {
            Message<String> message = MessageBuilder.withPayload(msg).build();
            String destination = topic + ":" + tags[i % tags.length];
            SendResult sendResult = rocketMQTemplate.sendMessageInTransaction(destination, message, destination);
            System.out.printf("%s%n", sendResult);
            Thread.sleep(10);
        }
    }
}
